﻿<template>
  <baseUI :isShow="myConfig.isShow" :label="myConfig.label" :showLabel="myConfig.showLabel" :labelSpan="myConfig.labelSpan" :isRequired="myConfig.isRequired" :showErrMsg="showErrMsg" :errMsg="errMsg" :commonConfig="commonConfig">
    <span :class="myConfig.isEnable?'span-show':'span-show-disabled'" :style="myConfig.myStyle">
      <template v-if="selectedText">
        <div class="div-text" v-if="myConfig.other.isMulti">
          <ul>
            <li v-for="(item, index) in selectedText" :key="index">
              <i>{{item}}</i>
            </li>
          </ul>
        </div>
        <div v-else class="div-text-single">
          {{selectedText.length > 0 ? selectedText[0] : ''}}
        </div>
      </template>
      <span v-if="myConfig.isEnable" @click="handleEdit" class="span-button">
        <i class="el-icon-edit"></i>
      </span>
    </span>
    <el-dialog v-drag
        :closeOnClickModal="false"
        :visible.sync="showPop"
        append-to-body
        width="50%"
        class="pop"
        :before-close="handleShowPopClose">
      <el-form v-if="myConfig.other.dataSource">
        <el-form-item>
          <template v-if="myConfig.other.dataSource.category === 'static'">
            <el-cascader-panel
            ref="ccselect"
            :options="myConfig.other.dataSource.StaticSettings.data"
            v-model = "ccValue"
            :props="{multiple: myConfig.other.isMulti, label: 'text', value: 'code', checkStrictly: true, emitPath: false}"></el-cascader-panel>
          </template>
          <template v-else-if="myConfig.other.dataSource.category === 'remote'">
            <el-cascader-panel
            ref="ccselect"
            v-model = "ccValue"
            :disabled = "!myConfig.isEnable"
            :clearable = "true"
            :separator="myConfig.other.separator ? myConfig.other.separator : '/'"
            placeholder = "请选择"
            :show-all-levels = 'true'
            calss="cc-select"
            :props="{multiple: myConfig.other.isMulti, checkStrictly: true, lazy: true, lazyLoad: initCascader, label: 'text', value: 'code', emitPath: false }"
            :style = "myConfig.myStyle">
            </el-cascader-panel>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitSelected" v-if="myConfig.isEnable">确定</el-button>
          <el-button type="info" @click="cancelSelected" v-if="myConfig.isEnable">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </baseUI>
</template>
<script>
import baseComponent from '../baseComponent.vue'
import baseUI from '../baseUI.vue'
export default {
  components: {
    baseComponent, baseUI
  },
  mixins: [baseComponent],
  mounted () {
    this.init(this.config)
  },
  data () {
    return {
      showPop: false,
      selectedText: [],
      ccValue: '',
      lctOptions: [{
        value: '',
        label: '选项'
      }]
    }
  },
  methods: {
    load (data) {
      this.lctOptions = []
    },
    getText () {
      return this.selectedText.join(',')
    },
    setValue (val) {
      if (this.selectedValue !== val) {
        this.selectedValue = val
        this.loadText()
      }
    },
    loadText () {
      if (this.selectedValue) {
        if (this.parentModel && this.parentModel[this.myConfig.dataKey + '__text']) {
          this.selectedText.push(this.parentModel[this.myConfig.dataKey + '__text'])
        } else {
          if (this.myConfig.other.dataSource.category === 'static') {
            this.setSelectedText4Static()
          } else {
            // 从后台获取对应的text
            let self = this
            if (this.myConfig.other.cadecaseCategory === 'ms') {
              this.$api.getMDFormCadecaseMSText({
                id: this.myConfig.other.dataSource.MetaPopSettings.table,
                column_name: this.myConfig.other.dataSource.MetaPopSettings.column,
                is_filter_deleted: this.myConfig.other.isFilterDeleted,
                value: this.selectedValue
              }).then(data => {
                if (data && data.data) {
                  data.data.forEach(d => {
                    self.selectedText.push(d.text.split('/').join(' ' + self.myConfig.other.separator + ' '))
                  })
                }
              })
            } else if (this.myConfig.other.cadecaseCategory === 'tree') {
              this.$api.getMDFormCadecaseTreeText({
                id: this.myConfig.other.dataSource.MetaPopSettings.table,
                column_name: this.myConfig.other.dataSource.MetaPopSettings.column,
                is_filter_deleted: this.myConfig.other.isFilterDeleted,
                value: this.selectedValue
              }).then(data => {
                if (data && data.data) {
                  data.data.forEach(d => {
                    self.selectedText.push(d.text.split('/').join(' ' + self.myConfig.other.separator + ' '))
                  })
                }
              })
            }
          }
        }
      } else {
        this.selectedText = []
      }
    },
    isDataComponent () {
      return true
    },
    initCascader (node, resolve) {
      if (!this.myConfig.other.dataSource ||
        !this.myConfig.other.dataSource.MetaPopSettings ||
        !this.myConfig.other.dataSource.MetaPopSettings.table ||
        !this.myConfig.other.dataSource.MetaPopSettings.column) return
      if (this.myConfig.other.cadecaseCategory === 'ms') {
        // 主从表的级联选择器
        if (node && node.data && node.data.code) {
          if (node.data.leaf) {
            resolve([]) // 叶子节点不需要再获取数据
            return
          }
          // 获取下一级的数据
          this.getCascaderMsData(node.data.code, node.level, resolve)
        } else {
          // 第一级时
          this.getCascaderMsData('', '', resolve)
        }
      } else if (this.myConfig.other.cadecaseCategory === 'tree') {
        // 单表的级联选择器
        if (node && node.data && node.data.code) {
          // 获取下一级的数据
          this.getCascaderTreeData(node.data.code, node.level, resolve)
        } else {
          // 第一级时
          this.getCascaderTreeData('', '', resolve)
        }
      }
    },
    // 获取主从表级联下拉框的内容，逐级获取
    getCascaderMsData (parent_pk, parent_level, resolve) {
      this.$api.mdFormCadecaseMSSelect({
        id: this.myConfig.other.dataSource.MetaPopSettings.table,
        column_name: this.myConfig.other.dataSource.MetaPopSettings.column,
        is_filter_deleted: this.myConfig.other.isFilterDeleted,
        parent_pk: parent_pk,
        parent_level: parent_level,
        start_meta_name: this.myConfig.other.dataSource.MetaPopSettings.startLevel.table,
        start_level_column: this.myConfig.other.dataSource.MetaPopSettings.startLevel.column,
        start_level_value: this.myConfig.other.dataSource.MetaPopSettings.startLevel.filterValue
      }).then(data => {
        let dataArray = []
        if (data.data.length) {
          data.data.forEach(item => {
            item['children'] = []
            item['leaf'] = data.is_last_level
            item['disabled'] = !item.can_select
            dataArray.push(item)
          })
        }
        resolve(dataArray)
      })
    },
    getCascaderTreeData (parent_pk, parent_level, resolve) {
      let self = this
      let orderExpress = {}
      if (self.myConfig.other.dataSource.MetaPopSettings.orderList) {
        self.myConfig.other.dataSource.MetaPopSettings.orderList.forEach((item, index) => {
          if (Object.keys(orderExpress).indexOf(item.column) < 0) {
            orderExpress[item.column] = 'asc'
          }
          orderExpress[item.column] = item.direction
        })
      }
      this.$api.mdFormCadecaseTreeSelect({
        id: this.myConfig.other.dataSource.MetaPopSettings.table,
        column_name: this.myConfig.other.dataSource.MetaPopSettings.column,
        is_filter_deleted: this.myConfig.other.isFilterDeleted,
        parent_pk: parent_pk,
        parent_level: parent_level,
        start_meta_name: this.myConfig.other.dataSource.MetaPopSettings.startLevel.table,
        start_level_column: this.myConfig.other.dataSource.MetaPopSettings.startLevel.column,
        start_level_value: this.myConfig.other.dataSource.MetaPopSettings.startLevel.filterValue,
        fixed_orderby_express: orderExpress,
        this_data: this.getDataObjFromPageModel(),
        ref_data: this.parentModel
      }).then(data => {
        let dataArray = []
        if (data.data.length) {
          data.data.forEach(item => {
            item['children'] = []
            dataArray.push(item)
          })
        }
        resolve(dataArray)
      })
    },
    handleShowPopClose () {
      this.showPop = false
    },
    handleEdit () {
      this.showPop = true
    },
    submitSelected () {
      this.selectedValue = this.ccValue
      let checkedNodes = this.$refs['ccselect'].getCheckedNodes()
      this.selectedText = []
      checkedNodes.forEach(node => {
        let arr = []
        node.pathNodes.forEach(pn => {
          arr.push(pn.data.text)
        })
        this.selectedText.push(arr.join(' ' + this.myConfig.other.separator + ' '))
      })
      this.showPop = false
      this.onChange()
    },
    cancelSelected () {
      this.showPop = false
    },
    getTextFormatList () {
      if (!this.myConfig.other.dataSource.StaticSettings.data) return []
      let list = JSON.parse(JSON.stringify(this.myConfig.other.dataSource.StaticSettings.data))
      let f = (node) => {
        if (node.children) {
          node.children.forEach(n => {
            n.selectedText = node.selectedText + ' ' + this.myConfig.other.separator + ' ' + n.text
            f(n)
          })
        }
      }
      list.forEach(n => {
        n.selectedText = n.text
        f(n)
      })
      return list
    },
    setSelectedText4Static () {
      if (!this.selectedValue) return ''
      let self = this
      let list = this.getTextFormatList()
      let f = (node) => {
        if (node.children) {
          node.children.forEach(n => {
            if (self.myConfig.other.isMulti) {
              let find = self.selectedValue.find(s => {
                return s === n.code
              })
              if (find) {
                self.selectedText.push(n.selectedText)
              }
            } else {
              if (self.selectedValue === n.code) {
                self.selectedText.push(n.selectedText)
              }
            }
          })
        }
      }
      list.forEach(n => {
        if (self.myConfig.other.isMulti) {
          let find = self.selectedValue.find(s => {
            return s === n.code
          })
          if (find) {
            self.selectedText.push(n.selectedText)
          }
        } else {
          if (self.selectedValue === n.code) {
            self.selectedText.push(n.selectedText)
          }
        }
        f(n)
      })
    }
  },
  watch: {
  }
}
</script>
<style lang="scss" scoped>
.span-show {
  display: flex;
  min-height: 30px!important;
  height: 30px;
  width: 100%;
  border: 1px solid #c0ccda;
  border-radius: 3px;
}
.span-show-disabled {
  display: flex;
  min-height: 30px!important;
  height: 30px;
  width: 100%;
  border: 1px solid #e4e7ed;
  color: #333 !important;
  border-radius: 3px;
  background-color: #f5f7fa;
}
.div-text {
  margin: 0 5px 0 0;
  width: 100%;
  overflow-y: auto;
  font-size: 15px;
}
.div-text-single {
  margin: 0 5px 0 0;
  width: 100%;
  overflow-y: hidden;
  font-size: 15px;
}

.span-button {
  font-size: 15px;
  width: 50px;
  display: flex;
  justify-content: center;
  border-left: 1px solid #c0ccda;
  background-color: #f5f7fa;
  cursor: pointer;
}
.span-button i {
  top: 30%;
  position: relative;
}
.cc-select {
  height: 300px;
  width: 100%;
}
</style>
